package com.foreveross.bsl.push.application.impl.channel.apns;

import java.io.ByteArrayInputStream;
import java.net.Proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.foreveross.bsl.push.domain.entity.channel.ApnsConfig;
import com.foreveross.bsl.push.domain.entity.channel.AppChannelConfig;
import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsService;
import com.notnoop.apns.ApnsServiceBuilder;

@Component
public class ApnsSandboxChannel extends ApnsChannel {

	private final static Logger log = LoggerFactory.getLogger(ApnsSandboxChannel.class);

	@Override
	public String getChannelId() {
		return "apns_sandbox";
	}

	@Override
	protected ApnsConfig getApnsConfig(String appId) {
		log.debug("获取APNS开发环境渠道的推送配置...");
		AppChannelConfig cfg = this.getAppChannelConfig(appId);
		return cfg.getApnsSandboxConfig();
	}

	@Override
	protected ApnsService buildApnsService(ApnsConfig apnsCfg) {
		//TODO BUG!!使用APNS client多线程模式，当证书被吊销时：
		//即出现异常Received fatal alert: certificate_revoked，且多个设备情况下,会导致应用僵死,待修复
		// 临时解决办法，更改过期证书并重启服务器
		ByteArrayInputStream certIs = new ByteArrayInputStream(apnsCfg.getCertContent());
		ApnsServiceBuilder asb = APNS.newService().withCert(certIs, apnsCfg.getCertPassword()).withDelegate(delegate)
				.withSandboxDestination().asPool(getPoolSize()).asQueued();
		Proxy proxy=this.getProxy();
		if(proxy != null) {
			log.info("渠道{}使用代理服务器:{}", this.getChannelId(), proxy.toString());
			asb.withProxy(proxy);
		}
		return asb.build();
	}

}
